import os
import json
import datetime
import time


def get_json_files():
    """获取当前目录下的所有json文件"""
    files = [f for f in os.listdir(".") if f.endswith(".json")]
    return files


def parse_json_file(filename):
    """解析json文件"""
    try:
        with open(filename, "r", encoding="utf-8") as f:
            data = json.load(f)
            for file, content in data.items():
                if "answer" in content:
                    first_answer = content["answer"][0]
                    if "txt" in first_answer:
                        first_txt = first_answer["txt"][0]
                        if "content" in first_txt:
                            components = first_txt["content"]["components"]
                            print(f"components: {components}")  # 调试输出
                            if components and isinstance(
                                components, list
                            ):  # 确保是列表
                                first_component = components[0]
                                if "data" in first_component:
                                    return first_component["data"]
                            else:
                                print(
                                    f"错误: components 不是列表，类型为 {type(components)}，值为 {components}"
                                )
    except Exception as e:
        print(f"解析 {filename} 时出错:", str(e))
        return None


def main():
    """主函数"""
    json_files = get_json_files()
    for file in json_files:
        data = parse_json_file(file)
        print(data)
        if data:
            # 获取列定义
            datas = data.get("datas", [])
            print(datas)
            timeStr = "[" + datetime.datetime.now().strftime("%Y%m%d") + "]"
            timeStr = "[20250224]"
            print(timeStr)
            stockArr = []
            # 处理涨停明细数据
            for item in datas:
                if 1:
                    objItem = {}
                    objItem["股票简称"] = item["股票简称"]
                    objItem["股票代码"] = item["code"]
                    objItem["涨停原因类别"] = item["涨停原因类别" + timeStr]
                    objItem["连续涨停天数"] = item["连续涨停天数" + timeStr]
                    objItem["几天几板"] = item["几天几板" + timeStr]
                    objItem["涨停类型"] = item["涨停类型" + timeStr]
                    ztData = json.loads(item["涨停明细数据" + timeStr])
                    first_limit_up = ztData[0]
                    highest_vol = max(ztData, key=lambda x: x["highestVol"])[
                        "highestVol"
                    ]
                    objItem["最新价"] = item["最新价"]
                    # objItem["首次涨停时间"] = time.strftime(
                    #     "%Y-%m-%d %H:%M:%S",
                    #     time.localtime(first_limit_up["time"] / 1000),
                    # )
                    objItem["首次涨停时间"] = item["首次涨停时间" + timeStr]
                    objItem["最终涨停时间"] = item["最终涨停时间" + timeStr]
                    objItem["涨停封单量"] = item["涨停封单量" + timeStr]
                    objItem["首次涨停量"] = first_limit_up["firstVol"]
                    objItem["最高涨停量"] = highest_vol
                    objItem["最高涨停金额"] = round(
                        float(highest_vol) * float(objItem["最新价"]) / 100000000,
                        2,
                    )
                    stockArr.append(objItem)
            import pandas as pd

            if stockArr:
                # 将数据转换为DataFrame格式
                df = pd.DataFrame(stockArr)

                # 生成Excel文件名 (使用JSON文件名但改为xlsx后缀)
                excel_filename = (
                    datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + ".xlsx"
                )

                # 保存为Excel文件
                df.to_excel("excel/" + excel_filename, index=False)
                print(f"已将 {file} 转换为 {excel_filename}")
            else:
                print(f"{file} 中没有数据")


if __name__ == "__main__":
    main()
